package org.njo.webapp.templates.servlet.wrapper;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;

/**
 * 
 * @author yu.peng
 */
public class StringResponseWrapper extends HttpServletResponseWrapper  {

    private ByteArrayOutputStream byteArrayOutputStream;
    private ServletOutputStream output;
    private PrintWriter writer;
    
    /**
     * 构造方法.
     *  
     * @param response HttpServletResponse对象
     * @param outFile  文件名
     * @throws IOException
     */
    public StringResponseWrapper(HttpServletResponse response, String charset) throws IOException {
        super(response);
        // 构造数据输出流
        byteArrayOutputStream = new ByteArrayOutputStream();
        output = new ServletOutputStreamWrapper(byteArrayOutputStream);
        // 构造Writer
        String charSetEncoding = (charset==null || "".equals(charset)) ? response.getCharacterEncoding() : charset;
        OutputStreamWriter outputStreamWriter = 
            new OutputStreamWriter(byteArrayOutputStream, charSetEncoding);
        writer = new PrintWriter(outputStreamWriter);
    }

    /**
     * 覆盖父类的getWriter方法.
     * 使输出转送到指定的文件中.
     */
    public PrintWriter getWriter() {
        return writer; 
    }
    
    /**
     * 覆盖父类的getOutputStream方法.
     * 使输出转送到指定的文件中.
     */
    public ServletOutputStream getOutputStream() throws java.io.IOException {
        return output;
    }
    
    public void close() throws IOException {
        writer.close();
        output.close();
    }
    public void flush() throws IOException {
        writer.flush();
        output.flush();
    }
    
    public String toString() {
        return new String(byteArrayOutputStream.toByteArray());
    }
    
}
